<script>
import {v4 as uuidv4} from 'uuid';

export default {
  name: "DefaultMendian",
  data() {
    return {
      //图片
      imageUrl: [],
      acceptData: '',
      fileName: '',
      currentFile: {},
      //上架区域的字
      span: ['全部门店', '上架中', '已下架'],
      spanColor: 'black',
      CurrentIndex: -1,
      //搜索框数据对象
      searchContent: {
        keyword: '',
        phone: '',
        shopStatus: '',
        time: [],
        pageNum: 1,
        pageSize: 10,
      },
      //表单数据对象
      tableData: [],
      //对话框的数据模型
      dialogFormVisible: false,
      url: 'https://restapi.amap.com/v3/geocode/geo?key=457886b5972a97e93fb9cdccebfd450f&address=',//经纬度axios
      formLabelWidth: '120px',  //输入框标题宽度
      from: {
        shopId: '',
        shopName: "",
        shopDescribe: "",
        shopImage: "",
        shopPhone: "",
        shopProvince: "",
        shopCity: "",
        shopDistrict: "",
        shopAddress: "",
        shopLongitude: "",
        shopLatitude: "",
        shopStatus: 1,
        addTime: "",
        shopUserId: '',
        shopAccount: null,
        shopPassword: null,
        shopSort: null,
        salesVolume: 0,
        distance: null,
        shopCommunitySort: null,
        concernStatus: null,
        shopOrderCount: 0,
        shopCategoryList: null,
        shopGoodsList: null,
        //获取省市数据
        addressAll: [],
        address: [],
        //经纬度坐标
        location: '',
        mode: 1//1增加  2修改
      },
      timerId: null,
      //行数据
      index: '',
      row: {},
      //page对象
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      }
    }
  },
  methods: {
    //搜索框点击发送请求函数
    searchClick() {
      let  startTime='';
      let endTime='';
      if (this.searchContent.time.length > 0) {
        startTime=this.searchContent.time[0] === undefined ? '' : this.formatDateTime(this.searchContent.time[0]);
        endTime=this.searchContent.time[1] === undefined ? '' : this.formatDateTime(this.searchContent.time[1]);
      }
      this.axios.get('http://localhost:8080/panghudaojiaBackend/shop/querySearchShopList',
          {
            params: {
              //传输的参数
              keyword: this.searchContent.keyword === undefined ? '' : this.searchContent.keyword,
              phone: this.searchContent.phone === undefined ? '' : this.searchContent.phone,
              pageNum: this.searchContent.pageNum === undefined ? '' : this.searchContent.pageNum,
              pageSize: this.searchContent.pageSize === undefined ? '' : this.searchContent.pageSize,
              startTime: startTime,
              endTime: endTime,
            }
          }
      ).then((res) => {
        //处理响应数据
        console.log(res);
        //真正需要的数据
        console.log(res.data.data.list);
        //将得到的数据加载到tableData
        this.tableData = res.data.data.list;
      }).catch(err => {
      })
    },
    //格式化日期函数
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //新增门店
    addShop() {
      this.dialogFormVisible = true;
    },
    //获取省市
    getAllProvinceAndCityList() {

      // 获取全国所有省份和城市的列表
      var that = this;
      this.$http
          .get("https://restapi.amap.com/v3/config/district", {
            // 高德地图的API
            params: {
              key: "2ebea716638964726dc72279f882d2e4", // 这个是申请的 Key，读者自行写入
              keywords: "中国",
              subdistrict: 3,
              extensions: "base",
            },
          })
          .then((response) => {
            console.log(response.data)


            for (let i = 0; i < response.data.districts[0].districts.length; i++) {
              let provinceMap = new Map();
              provinceMap.value = response.data.districts[0].districts[i].adcode;   //区域编号
              provinceMap.label = response.data.districts[0].districts[i].name;     //省名称
              provinceMap.children = [];
              that.addressAll.push(provinceMap);  //添加省份
              for (let j = 0; j < response.data.districts[0].districts[i].districts.length; j++) {
                let cityMap = new Map()
                cityMap.value = response.data.districts[0].districts[i].districts[j].adcode;   //区域编号
                cityMap.label = response.data.districts[0].districts[i].districts[j].name;     //市名称
                cityMap.children = [];
                provinceMap.children.push(cityMap); //添加市
                for (let k = 0; k < response.data.districts[0].districts[i].districts[j].districts.length; k++) {
                  let areaMap = new Map()
                  areaMap.value = response.data.districts[0].districts[i].districts[j].districts[k].adcode;   //区域编号
                  areaMap.label = response.data.districts[0].districts[i].districts[j].districts[k].name;     //区县名称
                  cityMap.children.push(areaMap);   //添加区县
                }
              }
            }
          });
    },
    //获取经纬度坐标
    getLocation() {
      this.axios.get(this.url + this.from.address.join('')).then((response) => {
        console.log(response)
        //axios会自己封装数据，得输出看看
        this.from.location = response.data.geocodes[0].location;
        let locationArr = this.from.location.split(',');
        //经纬度赋值,准备提交数据
        this.from.shopLatitude = locationArr[0];
        this.from.shopLongitude = locationArr[1];
      }).catch((err) => {
        console.log("请求出错")
      })
    },
    putFrom() {
      if (this.from.mode === 1) {
        //新增门店
        //处理省市
        this.dialogFormVisible = false;
        this.from.shopProvince = this.from.address[0];
        this.from.shopCity = this.from.address[1];
        this.from.shopDistrict = this.from.address[2];
        //将想要新增的数据发送请求
        this.axios.post('http://localhost:8080/panghudaojiaBackend/shop/addShop', {
          shopAddress: this.from.shopAddress,
          shopCity: this.from.shopCity,
          shopDescribe: this.from.shopDescribe,
          shopDistrict: this.from.shopDistrict,
          shopImage: this.from.shopImage,
          shopLatitude: this.from.shopLatitude,
          shopLongitude: this.from.shopLongitude,
          shopName: this.from.shopName,
          shopPhone: this.from.shopPhone,
          shopProvince: this.from.shopProvince,
        }).then(response => {
          console.log(response)
        }).catch(err => {
          console.log('请求失败')
        });
        this.clearFrom();
        //后台处理需要时间，直接刷新可能获取不到最新的数据
        this.timerId = setTimeout(this.flushTable, 500);
      } else if (this.from.mode === 2) {
        //修改
        this.dialogFormVisible = false;
        let locationArr = this.from.location.split('');
        this.from.shopLatitude = locationArr[0];
        this.from.shopLongitude = locationArr[1];

        this.axios.post("http://localhost:8080/panghudaojiaBackend/shop/modifyShop",
            {
              addTime: this.formatDateTime(new Date()),
              concernStatus: null,
              distance: this.row.distance,
              salesVolume: this.row.salesVolume,
              shopAccount: this.row.shopAccount,
              shopAddress: this.from.shopAddress,
              shopCategoryList: this.row.shopGoodsList,
              shopCity: this.from.address[1],
              shopCommunitySort: this.row.shopCommunitySort,
              shopDescribe: this.from.shopDescribe,
              shopDistrict: this.from.address[2],
              shopGoodsList: this.row.shopGoodsList,
              shopId: this.row.shopId,
              shopImage: this.from.shopImage,
              shopLatitude: this.from.shopLatitude,
              shopLongitude: this.from.shopLongitude,
              shopName: this.from.shopName,
              shopOrderCount: this.row.shopOrderCount,
              shopPassword: this.row.shopPassword,
              shopPhone: this.from.shopPhone,
              shopProvince: this.from.address[0],
              shopSort: this.row.shopSort,
              shopStatus: this.row.shopStatus,
              shopUserId: this.row.shopUserId
            }
        ).then((response) => {
        }).catch((err) => {
          console.log("修改失败")
        });
        this.clearFrom();
        //后台处理需要时间，直接刷新可能获取不到最新的数据
        this.timerId = setTimeout(this.flushTable, 500);
        this.from.mode = 1;
      }


    },
    //清空对话框数据
    clearFrom() {
      this.from.shopAddress = '';
      this.from.shopCity = '';
      this.from.shopDescribe = '';
      this.from.shopDistrict = '';
      this.from.shopImage = '';
      this.from.shopLatitude = '';
      this.from.shopLongitude = '';
      this.from.shopName = '';
      this.from.shopPhone = '';
      this.from.shopProvince = '';

    },
    //获取初始化表格数据
    flushTable() {
      this.axios.get('http://localhost:8080/panghudaojiaBackend/shop/querySearchShopList',
          {
            params: {
              //传输的参数
              keyword: '',
              phone: '',
              pageNum: 1,
              pageSize: 10,
              startTime: '',
              endTime: '',
            }
          }
      ).then((res) => {
        //处理响应数据
        console.log(res);
        //真正需要的数据
        // console.log(res.data.data.list);
        //将得到的数据加载到tableData
        this.tableData = res.data.data.list;
        // console.log(res.data.list);
        this.page.total = res.data.data.total;
        console.log(this.page.total);
      }).catch(err => {
      });
    },
    //上传图片之前
    beforeAvatarUpload(file) {
      console.log("上传之前")
      console.log(file);
      this.currentFile = file;
      //创建一个uuid
      this.fileName = uuidv4() + '.jpg';
      //需要传的参数设置为uuid
      this.from.shopImage = this.fileName;
      this.axios.get('http://43.143.190.87:8091/panghudaojiaBackend/qiniu/getQiniuUploadToken?fileName=' + encodeURIComponent(this.fileName))
          .then((res) => {
                console.log(res);
                //将许可证赋值
                this.acceptData = res.data.data;
                console.log("acceptData:" + this.acceptData);
              }
          ).catch(() => {
        console.log("请求出错")
      });
    },
    //上传成功之后
    handleAvatarSuccess(res) {
      // this.imageUrl = URL.createObjectURL(this.currentFile.raw);
      this.imageUrl = res.data.key;
    },
    //自定义上传
    customUpload() {

      setTimeout(this.cu, 500);


    },
    //自定义上传抽离
    cu() {
      const formData = new FormData();
      formData.append('file', this.currentFile);
      formData.append('key', this.fileName); // 假设这是你的文件名或路径
      formData.append('token', this.acceptData);// 假设这是你的上传令牌
      this.axios.post("https://up-z1.qiniup.com/", formData).then(response => {

      }).catch(() => {
        console.log("上传失败")
      })
    },
    //手动上传触发
    shoudong() {
      this.sd();
    },
    //手动抽离
    sd() {
      this.$refs.upload.submit()
    },
    //修改
    handleEdit(index, row) {
      this.index = index;
      this.row = row;
      this.from.mode = 2;
      this.initDialog(row);
      this.dialogFormVisible = true;

    },
    //初始化对话框
    initDialog(row) {
      this.from.shopAddress = row.shopAddress;
      this.from.shopCity = row.shopCity;
      this.from.shopDescribe = row.shopDescribe;
      this.from.shopDistrict = row.shopDistrict;
      this.from.shopImage = row.shopImage;
      this.from.shopLatitude = row.shopLatitude;
      this.from.shopLongitude = row.shopLongitude;
      this.from.shopName = row.shopName;
      this.from.shopPhone = row.shopPhone;
      this.from.shopProvince = row.shopProvince;
    },
    //页面底部导航
    nextClick() {//点击下一页
      this.page.currentPage++;
      this.axios.get('http://localhost:8080/panghudaojiaBackend/shop/querySearchShopList',
          {
            params: {
              pageNum: this.page.currentPage,
              pageSize: this.page.pageSize,
              phone: '',
              keyword: '',
              shopStatus: '',
              startTime: '',
              endTime: ''
            }
          }
      ).then((response) => {
        // console.log(response)
        //更新表格数据
        this.tableData = response.data.data.list;
        //设置total
        this.page.total = response.data.data.total
        // console.log(this.page.total)

      }).catch(err => {
      });
    },
    prevClick() {//点击上一页
      this.page.currentPage--;
      this.axios.get('http://localhost:8080/panghudaojiaBackend/shop/querySearchShopList',
          {
            params: {
              pageNum: this.page.currentPage,
              pageSize: this.page.pageSize,
              phone: '',
              keyword: '',
              shopStatus: '',
              startTime: '',
              endTime: ''
            }
          }
      ).then((response) => {
        // console.log(response)
        //更新表格数据
        this.tableData = response.data.data.list;
        //设置total
        this.page.total = response.data.data.total
        // console.log(this.page.total)

      }).catch(err => {
      });
    },
    currentChange(currentPage) {//点击任意页码
      console.log(currentPage);
      this.page.currentPage = currentPage;
      this.axios.get('http://localhost:8080/panghudaojiaBackend/shop/querySearchShopList',
          {
            params: {
              pageNum: this.page.currentPage,
              pageSize: this.page.pageSize,
              phone: '',
              keyword: '',
              shopStatus: '',
              startTime: '',
              endTime: ''
            }
          }
      ).then((response) => {
        console.log(response)
        //更新表格数据
        this.tableData = response.data.data.list;
        //设置total
        this.page.total = response.data.data.total
        console.log(this.page.total)

      }).catch(err => {
      });
    },

    //门店管理路由跳转
    handleRouter(index, row) {
      this.$router.push({path: "/help/mendian/manage",query:{id:row.shopId}}).catch();
    }

  },
  created() {
    //初始化获得表格数据
    this.flushTable()
    //初始化获得省市数据
    // this.getAllProvinceAndCityList();
  }

}
</script>

<template>
  <div class="mendian">
    <!--  上架-->
    <div class="sj">
      <span v-for="(v,i) in span" :key="v" :class="{active:i===CurrentIndex}" @click="CurrentIndex=i">{{ v }}</span>
    </div>
    <!-- 搜索框 -->
    <div class="searchAndDate cf">
      <div class="search">
        <span>门店名称：</span>
        <el-input v-model="searchContent.keyword" placeholder="请输入内容" class="searchInputSize"></el-input>
      </div>
      <div class="search">
        <span>门店手机号：</span>
        <el-input v-model="searchContent.phone" placeholder="请输入内容" class="searchInputSize"></el-input>
      </div>
      <div class="date">
        <span>提交日期：</span>
        <el-date-picker
            v-model="searchContent.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
        </el-date-picker>
      </div>
      <el-button type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
    </div>
    <!--  对话框-->
    <el-button type="primary" @click="addShop">新增门店</el-button>
    <el-dialog title="门店新增" :visible.sync="dialogFormVisible">
      <el-form :model="from">
        <!--      门店名称-->
        <el-form-item label="门店名称" :label-width="formLabelWidth">
          <el-input v-model="from.shopName" autocomplete="off"></el-input>
        </el-form-item>
        <!--      门店头像-->
        <el-form-item label="门店头像" :label-width="formLabelWidth">
          <el-upload
              ref="upload"
              class="avatar-uploader"
              action=""
              :data="{key:this.fileName,token:this.acceptData}"
              :show-file-list="true"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :auto-upload="false"
              :http-request="customUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-button size="small" type="primary" @click="shoudong">点击上传</el-button>
          <el-input v-model="from.shopImage" autocomplete="off"></el-input>
        </el-form-item>
        <!--      门店手机号-->
        <el-form-item label="门店手机号" :label-width="formLabelWidth">
          <el-input v-model="from.shopPhone" autocomplete="off"></el-input>
        </el-form-item>
        <!--        所属地区-->
        <el-form-item label="所属地区" :label-width="formLabelWidth">
          <div class="areabox">
            <el-cascader
                :options="from.addressAll"
                clearable
                v-model="from.address"
                :props="{value:'label'}"

            ></el-cascader>


            <h1>{{ from.address }}</h1>
            <h1>{{ from.address.join('') }}</h1>
          </div>
        </el-form-item>
        <!--  详细地址-->
        <el-form-item label="" :label-width="formLabelWidth">
          <el-input v-model="from.shopAddress" autocomplete="off" placeholder="请填写详细地址"></el-input>
          <!--  测试详细地址取值-->
          {{ from.shopAddress }}
        </el-form-item>

        <!--    获取坐标-->
        <el-form-item label="门店坐标" :label-width="formLabelWidth">
          <el-button type="primary" @click="getLocation">获取位置</el-button>
          {{ from.location }}
        </el-form-item>
        <!--      营业时间 -->
        <el-form-item label="营业时间" :label-width="formLabelWidth">
          <el-input v-model="from.shopDescribe" autocomplete="off"></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="putFrom">确 定</el-button>
      </div>
    </el-dialog>


    <!--  表格-->
    <div class="formTable">
      <el-table
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{'text-align': 'center',backgroundColor: '#1890ff',color:'#fff'}"
          :cell-style="{'text-align': 'center'}"
      >
        <el-table-column
            prop="shopName"
            label="门店"
            width="180">
        </el-table-column>
        <el-table-column
            prop="shopId"
            label="id"
            width="180">
        </el-table-column>
        <el-table-column
            prop="shopPhone"
            label="门店手机号">
        </el-table-column>
        <el-table-column
            prop="shopAddress"
            label="门店地址">
        </el-table-column>
        <el-table-column
            prop="shopDescribe"
            label="营业时间">
        </el-table-column>
        <el-table-column
            prop="communityName"
            label="关联小区">
        </el-table-column>
        <el-table-column
            prop="shopOrderCount"
            label="订单总数">
        </el-table-column>
        <el-table-column
            prop="concernStatus"
            label="提交方式">
        </el-table-column>
        <el-table-column
            prop="shopStatus"
            label="状态">
          <template v-slot="scope">
            <!-- 假设 shopStatus 为 1 时显示“上架”，否则显示“已下架” -->
            {{ scope.row.shopStatus === 1 ? '已上架' : '已下架' }}
          </template>
        </el-table-column>
        <el-table-column
            label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                @click="handleEdit(scope.$index, scope.row)">修改门店资料
            </el-button>
            <el-button
                size="mini"
                type="text"
                @click="handleRouter(scope.$index, scope.row)">门店管理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--  分页-->
    <div class="block">
      <el-pagination
          layout="prev, pager, next"
          :total="page.total"
          :page-size="page.pageSize"
          :current-page="page.currentPage"
          @next-click="nextClick"
          @prev-click="prevClick"
          @current-change="currentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<style scoped>
.mendian {
  height: 800px;
  background-color: yellowgreen;
}

.sj > span {
  margin-right: 20px;
}

.active {
  color: #00FFFF;
}

.search {
  width: 320px;
  height: 36px;
  margin-right: 20px;
  margin-bottom: 10px;
  float: left;
}

.date {
  width: 430px;
  height: 36px;
  margin-right: 20px;
  margin-bottom: 10px;
  float: left;
}

.searchInputSize {
  box-sizing: border-box;
  width: 200px;
  height: 36px;
  padding: 0 15px;
}

.searchAndDate {
  margin-top: 30px;
}

.areabox {
  width: 800px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;

}

/**/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>